package com.situ.hospital.doctor.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.json.JSONObject;

import com.situ.hospital.doctor.model.DoctorModel;
import com.situ.hospital.doctor.service.DoctorService;

/**
 * Servlet implementation class DoctorUploadServlet
 */
@WebServlet("/uploadServlet")
public class DoctorUploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Map<String, Object> map = null;
		try {
			map = upload(request);

		} catch (FileUploadException | IOException e) {
			e.printStackTrace();
		}
		List<String> list = (List<String>) map.get("list");
		String image = list.get(0);
		String id = (String) map.get("doctorid");

		DoctorModel doctor = new DoctorModel();
		doctor.setDoctorJpg(image);
		doctor.setDoctorId(Integer.parseInt(id));

		DoctorService ds = new DoctorService();
		Integer result=null;
		try {
			result=ds.update(doctor);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		Map<String,Object> backmap=new HashMap<>();
		backmap.put("result",result);
		backmap.put("image", image);
		
		JSONObject jso = new JSONObject(backmap);
		response.getWriter().print(jso);
		
		
	}

	public Map<String, Object> upload(HttpServletRequest request) throws FileUploadException, IOException {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		List<FileItem> items = upload.parseRequest(request);
		List<String> names = new ArrayList<>();
		Map<String, Object> map = new HashMap<>();
		for (FileItem fi : items) {
			if (fi.isFormField()) {
				String name = fi.getFieldName();
				String value = fi.getString();
				value = new String(value.getBytes("ISO-8859-1"), "UTF-8");
				map.put(name, value);
			} else {
				String fn = getFileName(fi);
				FileOutputStream fw = new FileOutputStream(getPath() + "/" + fn);
				byte[] b = new byte[1024 * 1024];
				int length = -1;
				InputStream is = fi.getInputStream();
				while (-1 != (length = is.read(b)))
					fw.write(b, 0, length);
				fw.flush();
				fw.close();
				is.close();
				names.add(fn);
			}
		}
		map.put("list", names);
		return map;
	}

	private static String getFileName(FileItem item) {
		String fn = item.getName();
		fn = UUID.randomUUID().toString() + fn.substring(fn.indexOf("."));
		return fn;
	}

	private static File getPath() {
		File f = new File("D:\\Study\\project\\java\\jpg");
		if (!f.exists()) {
			f.mkdir();
		}
		return f;
	}

}
